<?php

namespace app\erp\controller;

use app\admin\model\Customeraddress;
use app\admin\model\Synlogs;
use think\Log;

class Customer extends Base
{
    public function __construct($starttime, $endtime,$client_id,$client_secret,$account_id,$user_name)
    {
        parent::__construct($client_id, $client_secret,$account_id,$user_name);

        $this->starttime = $starttime;
        $this->endtime   = $endtime;
    }
    public function run($forg_fnumber,$forig_id,$page,$pageSize,$uuid)
    {

        $res = $this->getBizpersonGroupPage($forg_fnumber,$page,$pageSize,$uuid);

        if($res['code'] === 1)
        {
            $response = $this->insertDataAndUpdateSuper($res['data'], $forig_id,$uuid);

            if($response)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_successnums' => $response['total'],
                    'fk_bdl_status'      => "true",
                    'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
                ]);
                Log::info('客户成功,'. "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forg_fnumber . "参数：" . json_encode($res['data']));

                return "组织编码".$forg_fnumber . ':本次成功同步条数' . $response['total'];

            }
        }elseif ($res['code'] === 2) {
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_successnums' => 0,
                'fk_bdl_status'      => "true",
                'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
            ]);
            return "组织编码".$forg_fnumber . ':本次成功同步条数0';

        }

    }

    private function getBizpersonGroupPage($createorg_number, $pageNo, $pageSize,$uuid)
    {
        $method  = "v2/bdl/bdl_comm_basedata/bdl_bd_customer/queryCustomer";

        $fullurl = $this->url . $method;


        Synlogs::where('id',$uuid)->update([
            'fk_bdl_url'        => $fullurl,

        ]);

        $response_data = [
            'data'      => [
                'starttime'             => $this->starttime,
                'endtime'               => $this->endtime,
                'createorg_number'      => $createorg_number,
            ],
            'pageNo'    => $pageNo,
            'pageSize'  => $pageSize,
        ];

        $this->curl->setHeader("Content-Type", "application/json");
        $this->curl->setHeader("accesstoken", $this->getToken());
        $this->curl->setHeader("Idempotency-Key", uuid());

        $res = $this->curl->post($fullurl, json_encode($response_data));

        if ($res && is_object($res) && $res->status == 1)
        {
            if($res->data->totalCount > 0){

                return [
                    'data' => $res->data->rows,
                    'code'  => 1

                ];
            }else{
                return [
                    'code'  => 2,
                ];
            }

        }else{
            if(strlen($res->message) > 255)
            {
//                $res->message = substr($res->message,0,155);

                return $this->error( 'aaaaaaaa'  . request()->action() .  $res->message);

            }
            if(property_exists($res,'errorCode') && $res->errorCode == 404)
            {
                return $this->error( 'aaaaaaaa'  . request()->action() .  $res->message);
            }

            Synlogs::where('id',$uuid)->update([
                'fk_bdl_exceptionmsg'   => $res->message,
                'fk_bdl_status'         => "false",
            ]);
            Log::info('客户同步失败,'  . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $createorg_number . "参数：" . json_encode($response_data));
            return [
                'data' => false,
                'code'  => 0
            ];
        }


    }

    private function insertDataAndUpdateSuper($data, $forgid,$uuid)
    {
        $count = 0;

        if(!empty($data))
        {
            try {
                // 组装 data 并插入
                foreach ($data as $k => $v)
                {

                    //判断是否已经存在
                    $isExist = \app\admin\model\Customer::where('fnumber', $v->number)->where('fk_bdl_bd_datacenter',$this->account_id)->where('forgid',$forgid)->find();

                    $insertData = [
                        'fname'                             => !empty($v->name) ? $v->name : ' ',
                        'fnumber'                           => !empty($v->number) ? $v->number : ' ',
                        'fenable'                           => $v->enable,
                        'forgid'                            => $forgid,
                        'fk_bdl_createtime'                 => $v->createtime,
                        'fk_bdl_modifytime'                 =>  $v->modifytime,
                        'fk_bdl_bd_datacenter'              => $this->account_id,
                        'fk_bdl_bd_bizpersonnum'             => !empty($v->bdl_bd_salesperson_number) ? $v->bdl_bd_salesperson_number : ' ',
                        'fk_bdl_telephone'                  => !empty($v->bdl_telephone) ? $v->bdl_telephone : ' ',
                        'fk_bdl_bd_industry'                => !empty($v->bdl_bd_industry_name) ? $v->bdl_bd_industry_name : ' ',
                        'fk_bdl_legalphone'                 => !empty($v->bdl_legalphone) ? $v->bdl_legalphone : ' ',
                        'fk_bdl_position'                   => !empty($v->bdl_position_title) ? $v->bdl_position_title : ' ',
                        'fk_bdl_nature'                     => !empty($v->bdl_nature_title) ? $v->bdl_nature_title : ' ',
                        'fk_bdl_bd_customergrade'           => !empty($v->bdl_bd_customergrade_name) ? $v->bdl_bd_customergrade_name : ' ',
                        'fk_bdl_shortname'                  => !empty($v->bdl_shortname) ? $v->bdl_shortname : ' ',
                        'fk_bdl_mailaddress'                => !empty($v->bdl_mailaddress) ? $v->bdl_mailaddress : ' ',
                        'fk_bdl_contacts'                   => !empty($v->bdl_contacts) ? $v->bdl_contacts : ' ',
                        'fk_bdl_legalperson'                => !empty($v->bdl_legalperson) ? $v->bdl_legalperson : ' ',
                        'fk_bdl_comment'                    => !empty($v->group_number) ? $v->group_number : ' ',
                        'fk_bdl_addressjsondata'            => json_encode($v->bdl_entry)
                    ];


                    if(!empty($isExist))
                    {

                        unset($insertData['forgid']);
                        unset($insertData['fk_bdl_bd_datacenter']);
                        \app\admin\model\Customer::where('id',$isExist['id'])->update($insertData);
                    }else{

                        \app\admin\model\Customer::create($insertData);

                    }

                    $count++;

                }

                // 插入成功后 更新业务员
                $this->updateBizoersonCategory($forgid);
                // 插入成功后 更新客户组
                $this->updateCustomerCategory($forgid);
                // 插入成功后 更新地址
                $this->updateAddressCategory($forgid);
            }catch (\Exception $e)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_exceptionmsg' => $e->getMessage(),
                    'fk_bdl_status'         => "false",
                ]);
                Log::error('客户同步失败,'. $e->getMessage() . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forgid . "参数：" . json_encode($data));

                $this->error( 'aaaaaaaa'  . request()->action() .  $e->getMessage());


            }
        }

        return [
            'code'      =>1,
            'total'     => $count,
        ];

    }

    //更新业务员
    public function updateBizoersonCategory($forgid)
    {
        $data = \app\admin\model\Customer::where('fk_bdl_bd_datacenter',$this->account_id)->whereNotNull('fk_bdl_bd_bizpersonnum')->select();

        foreach ($data as $k=>$v)
        {
            if(!empty($v['fk_bdl_bd_bizpersonnum']))
            {
                $super = \app\admin\model\Bizperson::where('fnumber',$v['fk_bdl_bd_bizpersonnum'])->where('fk_bdl_bd_datacenter',$this->account_id)->find();

                if($super)
                {
                    \app\admin\model\Customer::where('id', $v['id'])->update(['fk_bdl_bd_salesperson' => $super['id']]);
                }
            }
        }
    }

    //更新客户分类
    public function updateCustomerCategory($forgid)
    {
        $data = \app\admin\model\Customer::where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->whereNotNull('fk_bdl_comment')->whereNull('fk_bdl_bdgroup')->select();

        foreach ($data as $k=>$v)
        {
            $super = \app\admin\model\Customercate::where('fnumber',$v['fk_bdl_comment'])->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

            if($super)
            {
                \app\admin\model\Customer::where('id', $v['id'])->update(['fk_bdl_bdgroup' => $super['id']]);
            }
        }
    }

    //更新地址
    public function updateAddressCategory($forgid)
    {
        $data = \app\admin\model\Customer::where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->whereNotNull('fk_bdl_addressjsondata')->select();

        foreach ($data as $k=>$v)
        {
            if(!empty($v['fk_bdl_addressjsondata']))
            {
                //客户地址
                $address_jsondata = json_decode($v['fk_bdl_addressjsondata'],true);

                if(!empty($address_jsondata))
                {
                    foreach ($address_jsondata as $a=>$b)
                    {
                        //对比
                        $isExits = Customeraddress::where('fnumber',$b['bdl_bd_cusaddresse_number'])->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

                        if(!empty($isExits))
                        {
                            //更新
                            $updateData = [
                                'fk_bdl_bd_cusaddress'      => !empty($b['bdl_bd_cusaddresse_name']) ? $b['bdl_bd_cusaddresse_name'] : ' ',
                                'bdl_contacts'              => !empty($b['bdl_bd_cusaddresse_bdl_contacts']) ? $b['bdl_bd_cusaddresse_bdl_contacts'] : ' ',
                                'fk_bdl_phone'              => !empty($b['bdl_bd_cusaddresse_bdl_telephone']) ? $b['bdl_bd_cusaddresse_bdl_telephone'] : ' ',
                                'forgid'                    => $forgid,
                                'fk_bdl_bd_datacenter'      => $this->account_id,
                                'fk_bdl_province'           => !empty($b['bdl_bd_cusaddresse_bdl_province']) ? $b['bdl_bd_cusaddresse_bdl_province'] : ' ',
                                'fk_bdl_city'               => !empty($b['bdl_bd_cusaddresse_bdl_city']) ? $b['bdl_bd_cusaddresse_bdl_city'] : ' ',
                                'fk_bdl_region'             => !empty($b['bdl_bd_cusaddresse_bdl_region']) ? $b['bdl_bd_cusaddresse_bdl_region'] : ' ',
                                'fk_bdl_bd_customer'        => $v['id']
                            ];

                            Customeraddress::where('id',$isExits['id'])->update($updateData);
                        }else{
                            //新增
                            $data = [
                                'fk_bdl_bd_cusaddress'      => !empty($b['bdl_bd_cusaddresse_name']) ? $b['bdl_bd_cusaddresse_name'] : ' ',
                                'bdl_contacts'              => !empty($b['bdl_bd_cusaddresse_bdl_contacts']) ? $b['bdl_bd_cusaddresse_bdl_contacts'] : ' ',
                                'fk_bdl_phone'              => !empty($b['bdl_bd_cusaddresse_bdl_telephone']) ? $b['bdl_bd_cusaddresse_bdl_telephone'] : ' ',
                                'forgid'                    => $forgid,
                                'fk_bdl_bd_datacenter'      => $this->account_id,
                                'fnumber'                   => !empty($b['bdl_bd_cusaddresse_number']) ? $b['bdl_bd_cusaddresse_number'] : ' ',
                                'fk_bdl_province'           => !empty($b['bdl_bd_cusaddresse_bdl_province']) ? $b['bdl_bd_cusaddresse_bdl_province'] : ' ',
                                'fk_bdl_city'               => !empty($b['bdl_bd_cusaddresse_bdl_city']) ? $b['bdl_bd_cusaddresse_bdl_city'] : ' ',
                                'fk_bdl_region'             => !empty($b['bdl_bd_cusaddresse_bdl_region']) ? $b['bdl_bd_cusaddresse_bdl_region'] : ' ',
                                'fk_bdl_bd_customer'        => $v['id']
                            ];

                            Customeraddress::create($data);
                        }

                    }

                }


            }

        }
    }

}